package com.web.filter;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//1——继承HttpFilter
//2——重写doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
//3——注册过滤器，过滤哪个地址
//4——设置过滤器初始化局部参数
//5——重写init(FilterConfig config)方法获取init-param的参数
//6——静态页面不要过滤【避免乱码】
public class MyUTF8Filter extends HttpFilter {

    //创建FilterConfig对象
    FilterConfig config;

    /**
     * @param req   请求对象
     * @param res   响应对象
     * @param chain 过滤链条
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        String requestURI = req.getRequestURI();
        System.out.println("准备请求：" + requestURI + "........................");
        System.out.println("原本的字符集:" + req.getCharacterEncoding());
        //编写过滤器逻辑
        String encoding = config.getInitParameter("encoding");
        String contentType = config.getInitParameter("contentType");
        req.setCharacterEncoding(encoding);
        res.setContentType(contentType);
        //放行doFilter()
        chain.doFilter(req, res);
        System.out.println("服务端响应：" + requestURI + "........................");
    }
    @Override
    public void init(FilterConfig config) throws ServletException {
        //获取FilterConfig对象
        this.config = config;
    }
}
